<?php

namespace app\admin\controller\platform\task;

use app\BaseController;
use app\model\ConfigModel;
use app\model\platform\PlatformTaskContinuousEvaluationModel;
use app\model\platform\PlatformTaskModel;
use app\model\platform\PlatformTaskRatingScaleModel;
use app\model\platform\PlatformTaskUnitModel;
use app\model\TaskContinuousEvaluationModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\TaskUserModel;
use think\App;

class UseTask extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new PlatformTaskModel();
    }

    /**
     * 任务列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $PlatformTaskRatingScaleModel = new PlatformTaskRatingScaleModel();
            $PlatformTaskContinuousEvaluationModel = new PlatformTaskContinuousEvaluationModel();
            $task_id = $this->mode->where('status','=',2)->column('id');
            $where[] = ['task_id','in',$task_id];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $data = $PlatformTaskUnitModel->where($where)->with([
                'UnitTaskInfo' => function ($query) {
                    $query->with(['userName']);
                },
                'task' => function ($query) {
                    $query->with(['user']);
                }
            ])->order('id', 'desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$v) {
                $v['role_name'] = match ($v['user_level']) {
                    1 => '省级平台管理员',
                    2 => '市级平台管理员',
                    3 => '区级平台管理员'
                };
                //量表
                $TaskRatingScaleList = $PlatformTaskRatingScaleModel->where('task_id','=', $v['task_id'])
                    ->with([
                        'ratingScale',
                    ])->select()->toArray();
                $factorList = $PlatformTaskContinuousEvaluationModel->where('task_id','=', $v['task_id'])
                    ->with([
                        'ContinuityRatingScale', 'RatingScaleFactor'
                    ])->select()->toArray();
                $factorData = [];
                foreach ($factorList as $item) {
                    $factorData[$item['rating_scale_id']][] = [
                        'factor_id' => $item['factor_id'],
                        'factor_name' => $item['factor_name'],
                        'rating_scale_id' => $item['continuity_rating_scale_id'],
                        'rating_scale_name' => $item['continuity_rating_scale_name'],
                    ];
                }
                $rating_scale = [];
                foreach ($TaskRatingScaleList as $item) {
                    $rating_scale[] = [
                        'id' => $item['rating_scale_id'],
                        'name' => $item['rating_scale_name'],
                        'factor' => $factorData[$item['rating_scale_id']] ?? []
                    ];
                }
                $v['rating_scale'] = $rating_scale;
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 创建任务
     * @return bool|string
     */
    public function CreateTask(): bool|string
    {
        $this->mode->startTrans();
        try {
            $id = $this->request->param('id');
            $taskData = $this->request->param('task');
            $rating_scale = $this->request->param('rating_scale');
            $uids = $this->request->param('uids');
            $this->validate($taskData, [
                'name|任务名称' =>  'require',
                'start_time|开始时间' =>  'require',
                'end_time|结束时间' =>  'require',
            ]);
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $PlatformTaskUnitInfo = $PlatformTaskUnitModel->find($id);
            if (!$PlatformTaskUnitInfo) throw new \Exception('参数错误！');
            $taskData['channel'] = 2;
            $taskData['is_time'] = 1;
            if (empty($uids) || empty($rating_scale)) throw new \Exception('请选择量表和用户！');
            $rating_scale_column = array_column($rating_scale, 'id');
            if (count($rating_scale_column) !== count(array_unique($rating_scale_column))) throw new \Exception('量表不能重复选择！');
            $taskData['rating_scale_count'] = count($rating_scale);
            $taskData['user_count'] = count($uids);
            $taskData['unit_id'] = $this->userData['unit_id'];
            $taskData['uid'] = $this->userData['id'];
            $taskData['time'] = $time = time();
            if ($taskData['start_time'] >= $time && $taskData['end_time'] <= $time) {
                //在任务时间内将任务设为进行中
                $taskData['status'] = 2;
            }
            if (!empty($taskData['result_read_auth'])) {
                $taskData['result_read_auth'] = implode(',', $taskData['result_read_auth']);
            }
            $ConfigModel = new ConfigModel();
            $data = $ConfigModel->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => 'evaluation_task'
            ])->value('value') ?? '';
            $config = json_decode($data, true);
            $taskData['is_continuous'] = $config['is_continuous'] ?? 0;
            $taskData['is_redo'] = $config['is_redo'] ?? 0;
            $taskData['is_temporary'] = $config['is_temporary'] ?? 0;
            $TaskModel = new TaskModel();
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $TaskUserModel = new TaskUserModel();
            $TaskContinuousEvaluation = new TaskContinuousEvaluationModel();
            $task_id = $TaskModel->insertGetId($taskData);
            $PlatformTaskUnitInfo->unit_task_id = $task_id;
            $PlatformTaskUnitInfo->save();
            //添加任务量表和任务用户
            $task_user = [];
            $task_rating_scale = [];
            $continuousData = [];
            foreach ($rating_scale as $item) {
                //预警连续测评
                $factor = $item['factor'] ?? [];
                $factor_id_column = array_column($factor, 'factor_id');
                if (count($factor_id_column) !== count(array_unique($factor_id_column))) throw new \Exception('连评因子不能重复选择！');
                foreach ($factor as $value) {
                    if ($item['id'] == $value['rating_scale_id']) throw new \Exception('预警连评量表不能和测评量表一样');
                    $continuousData[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'factor_id' => $value['factor_id'],
                        'continuity_rating_scale_id' => $value['rating_scale_id'],
                        'time' => $time
                    ];
                }
                //任务量表
                $task_rating_scale[] = [
                    'task_id' => $task_id,
                    'rating_scale_id' => $item['id'],
//                    'pack_id' => $item['pack_id'],
                    'time' => $time
                ];
                //任务用户
                foreach ($uids as $uid) {
                    $task_user[] = [
                        'task_id' => $task_id,
                        'rating_scale_id' => $item['id'],
                        'uid' => $uid,
                        'time' => $time
                    ];
                }
            }
            if (!empty($continuousData)) {
                $TaskContinuousEvaluation->insertAll($continuousData);
            }
            if (!empty($task_user)) {
                $TaskUserModel->insertAll($task_user,200);
            }
            if (!empty($task_rating_scale)) {
                $TaskRatingScaleModel->insertAll($task_rating_scale);
            }
            $this->mode->commit();
            return success([], '添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 上交报告
     * @return bool|string
     */
    public function SubmitReport(): bool|string
    {
        $PlatformTaskUnitModel = new PlatformTaskUnitModel();
        $PlatformTaskUnitModel->startTrans();
        try {
            $id = $this->request->param('id');
            $info = $PlatformTaskUnitModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info->is_submit = 1;
            $info->submit_time = time();
            $info->submit_uid = $this->userData['id'];
            $info->save();
            $TaskModel = new TaskModel();
            $PlatformTaskModel = new PlatformTaskModel();
            $task_info = $PlatformTaskModel->find($info['task_id']);
            $unit_task_info = $TaskModel->find($info['unit_task_id']);
            if (!$task_info || !$unit_task_info) throw new \Exception('参数错误！');
            $unit_complete_num = $task_info->unit_complete_num + 1;
            $unit_complete_rate = round($unit_complete_num/$task_info->unit_count,2);
            $task_info->inc('warning_num',$unit_task_info->warning_num)->inc('user_count',$unit_task_info->user_count)->save([
                'unit_complete_num' => $unit_complete_num,
                'unit_complete_rate' => $unit_complete_rate
            ]);
            $unit_task_info->save([
                'status' => 3
            ]);
            $PlatformTaskUnitModel->commit();
            return success([],'提交成功！');
        } catch (\Exception $e) {
            $PlatformTaskUnitModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除任务
     * @return bool|string
     */
    public function del(): bool|string
    {
        $PlatformTaskUnitModel = new PlatformTaskUnitModel();
        $PlatformTaskUnitModel->startTrans();
        try {
            $id = $this->request->param('id');
            $info = $PlatformTaskUnitModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            if ($info->is_submit == 1) throw new \Exception('已上交任务，不可删除！');
            $TaskModel = new TaskModel();
            $TaskModel->where('id','=', $info->unit_task_id)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $info->unit_task_id = 0;
            $info->save();
            $PlatformTaskUnitModel->commit();
            return success([],'删除成功！');
        } catch (\Exception $e) {
            $PlatformTaskUnitModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 终止任务
     * @return bool|string
     */
    public function end(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $PlatformTaskUnitModel = new PlatformTaskUnitModel();
            $info = $PlatformTaskUnitModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $TaskModel = new TaskModel();
            $TaskModel->where('id','=', $info->unit_task_id)->update([
                'status' => 3
            ]);
            return success([],'终止成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


}